<script lang="ts" setup>
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { defaultUser, fetchUserDetail, fetchUserDetailByName, updateUser } from '@/services/api'
import { useUserStore } from '@/state/modules/user'
import { HideLoading, Loading, Toast } from '@/utils/uniapi/prompt'
import { getUploadUrl } from '@/utils/env'
import type { file } from '@/tmui/components/tm-upload/upload'
import tmForm from '@/tmui/components/tm-form/tm-form.vue'
import { useRouter } from '@/hooks/router'

const userStore = useUserStore()
const user = ref({ ...defaultUser })
const avatarList = ref<file[]>([])

const uploadMoveHandle = (item: file) => {
  console.log(item)
  user.value.avatarUrl = ''
  return true
}
const uploadSuccessHandle = (item: file) => {
  console.log(item)
  const response = item.response
  let isOk = false
  try {
    const data = JSON.parse(response)
    console.log(data)
    user.value.avatarUrl = data?.absUrl || ''
    isOk = !!data?.absUrl
  }
  catch { }

  return isOk
}

const form = ref<InstanceType<typeof tmForm> | null>(null)
const router = useRouter()
const confirm = async (e: any) => {
  console.log(e)
  if (!e?.isPass) {
    Toast('请检查表单内容是否完整', { icon: 'error' })
    return
  }
  Loading('loading...')
  const { error, data } = await updateUser(user.value)
  HideLoading()
  if (error) {
    Toast(error.msg, { icon: 'error' })
    return
  }
  userStore.userInfo.avatarUrl = data.avatarUrl
  userStore.userInfo.name = data.name
  userStore.userInfo.phoneNumber = data.phoneNumber
  userStore.userInfo.email = data.email
  userStore.userInfo.description = data.description
  Toast('修改成功', { icon: 'success' })
  setTimeout(() => router.back(), 1000)
}

onLoad(async (e) => {
  const id: string = e?.id || userStore.userInfo.id || ''
  if (id) {
    Loading('loading..')
    const { error, data } = await fetchUserDetail(id)
    HideLoading()
    if (!error) {
      user.value = data
      data.avatarUrl
      && avatarList.value.push({
        name: '',
        url: data.avatarUrl,
        progress: 100,
        response: '',
        status: '',
        statusCode: 3,
        uid: new Date().getTime(),
      })
    }
  }
  else {
    const userName = e?.userName || userStore.userInfo.userName || ''
    Loading('loading..')
    const { error, data } = await fetchUserDetailByName(userName)
    HideLoading()
    if (!error)
      user.value = data
  }
})
</script>

<template>
  <tm-app>
    <tm-form ref="form" v-model="user" :margin="[0]" :label-width="190" @submit="confirm">
      <tm-form-item label="账号" :margin="[0]" field="userName">
        <tm-input
          v-model.lazy="user.userName"
          :input-padding="[0, 0]"
          :transprent="true"
          disabled
        />
      </tm-form-item>

      <tm-form-item required label="姓名" :margin="[0]" field="name" :rules="[{ required: true, message: '必填且不能少于2个字', validator: (val: string) => val && val.length > 2 }]">
        <tm-input
          v-model.lazy="user.name"
          :input-padding="[0, 0]"
          :transprent="true"
        />
      </tm-form-item>

      <tm-form-item label="头像" align="flex-row-top-start" :margin="[0]" field="avatarUrl">
        <tm-upload
          v-model="avatarList"
          :rows="3"
          :width="420"
          :default-value="avatarList"
          :url="getUploadUrl()"
          :max-file="1"
          :show-status="false"
          :on-remove="uploadMoveHandle"
          :on-success-after="uploadSuccessHandle"
        />
        <tm-text label="支持 jpg|png|bmp，最大不超过2MB" :font-size="24" color="grey" parent-class="uno-mt-10px" />
      </tm-form-item>

      <tm-form-item label="电子邮件" :margin="[0]" field="email">
        <tm-input
          v-model.lazy="user.email"
          :input-padding="[0, 0]"
          :transprent="true"
        />
      </tm-form-item>

      <tm-form-item
        required
        label="联系方式"
        field="phoneNumber"
        :margin="[0]"
        :rules="[{ required: true, message: '必填' }]"
      >
        <tm-input
          v-model.lazy="user.phoneNumber"
          :maxlength="11"
          :input-padding="[0, 0]"
          :transprent="true"
        />
      </tm-form-item>

      <tm-form-item label="描述" align="flex-row-top-start" :margin="[0]" field="description">
        <tm-input
          v-model.lazy="user.description"
          type="textarea"
          :input-padding="[0, 0]"
          :transprent="true"
          :height="100"
        />
      </tm-form-item>
    </tm-form>

    <tm-sheet :margin="[0]" :transprent="true">
      <tm-button label="保存" block @click="form?.submit()" />
    </tm-sheet>
  </tm-app>
</template>

<style lang="scss" scoped></style>
